<template>
  <div class="employment-statistics-container">
    <n-h3 style="margin: 0 0 16px 0;">📊 学生就业信息统计</n-h3>
    
    <!-- 筛选条件 -->
    <div class="filter-section">
      <n-radio-group v-model:value="activeTab" name="tabGroup" style="margin-bottom: 20px;">
        <n-radio-button
          v-for="tab in tabs"
          :key="tab.value"
          :value="tab.value"
          :label="tab.label"
        />
      </n-radio-group>
      
      <div class="filter-controls">
        <!--
        <n-select v-model:value="selectedYear" :options="yearOptions" placeholder="选择年份" style="width: 120px; margin-right: 10px;" />
        <n-select v-model:value="selectedGrade" :options="gradeOptions" placeholder="选择年级" style="width: 120px; margin-right: 10px;" />
        -->
        <n-select v-model:value="selectedCollege" :options="collegeOptions" placeholder="选择学院" style="width: 150px; margin-right: 10px;" />
        <n-select v-model:value="selectedMajor" :options="majorOptions" placeholder="选择专业" style="width: 150px;" />
      </div>
    </div>
    
    <!-- 图表类型选择 -->
    <div v-if="activeTab === 'city'" class="chart-type-section">
      <n-radio-group v-model:value="chartType" name="chartType" style="margin-bottom: 20px;">
        <n-radio-button
          v-for="type in chartTypes"
          :key="type.value"
          :value="type.value"
          :label="type.label"
        />
      </n-radio-group>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" style="text-align: center; padding: 50px;">
      <n-spin size="large" />
      <div style="margin-top: 10px; color: #666;">数据加载中...</div>
    </div>
    
    <!-- 图表展示区域 -->
    <div v-else class="chart-wrapper">
      <!-- 就业地市图谱 -->
      <div v-if="activeTab === 'city'">
        <div v-if="chartType === 'map'" class="map-container">
          <v-chart
            :option="mapOption"
            autoresize
            style="background-color: #ffffff; height: 600px; border-radius: 8px;"
          />
        </div>
        <div v-else class="chart-container">
          <v-chart
            :option="chartOption"
            autoresize
            style="background-color: #ffffff; height: 500px; border-radius: 8px;"
          />
        </div>
      </div>
      
      <!-- 岗位性质统计 -->
      <div v-if="activeTab === 'nature'">
        <div class="chart-container">
          <v-chart
            :option="natureChartOption"
            autoresize
            style="background-color: #ffffff; height: 500px; border-radius: 8px;"
          />
        </div>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-area">
      <n-data-table
        :columns="columns"
        :data="tableData"
        :bordered="true"
        style="margin-top: 10px;"
      />
      
      <div class="pagination-wrapper">
        <n-pagination
          v-model:page="pagination.page"
          :page-count="pagination.pageCount"
          :page-size="pagination.pageSize"
          @update:page="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import {
  NH3,
  NRadioGroup,
  NRadioButton,
  NDataTable,
  NPagination,
  NSpin,
  NSelect
} from 'naive-ui'
import { use, registerMap } from 'echarts/core'
import { BarChart, LineChart, PieChart, MapChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DataZoomComponent,
  VisualMapComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
import chinaMap from "@/api/getChinaMap"
import convertProvince from "@/tools/convertProvince"

import {
  getEmploymentCityStats,
  getEmploymentNatureStats
} from "@/api/employment"

use([
  BarChart,
  LineChart,
  PieChart,
  MapChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DataZoomComponent,
  VisualMapComponent,
  CanvasRenderer
])

// 选项卡配置
const tabs = ref([
  { label: '就业地市图谱', value: 'city' },
  { label: '岗位性质统计', value: 'nature' }
])

const activeTab = ref('city')

// 图表类型配置
const chartTypes = ref([
  { label: '地图模式', value: 'map' },
  { label: '柱状图', value: 'bar' },
  { label: '折线图', value: 'line' },
  { label: '堆积图', value: 'stack' },
  { label: '数据视图', value: 'data' }
])

const chartType = ref('map')

// 筛选条件
// const selectedYear = ref(null)
// const selectedGrade = ref(null)
const selectedCollege = ref(null)
const selectedMajor = ref(null)

// const yearOptions = ref([
//   { label: '2024年', value: 2024 },
//   { label: '2023年', value: 2023 },
//   { label: '2022年', value: 2022 }
// ])

// const gradeOptions = ref([
//   { label: '2020级', value: 2020 },
//   { label: '2021级', value: 2021 },
//   { label: '2022级', value: 2022 },
//   { label: '2023级', value: 2023 }
// ])

const collegeOptions = ref([
  { label: '农学院', value: '农学院' },
  { label: '植物保护学院', value: '植物保护学院' },
  { label: '资源与环境学院', value: '资源与环境学院' },
  { label: '林学院', value: '林学院' },
  { label: '园艺科学与工程学院', value: '园艺科学与工程学院' }
])

const majorOptions = ref([
  { label: '农学', value: '农学' },
  { label: '植物保护', value: '植物保护' },
  { label: '环境科学', value: '环境科学' },
  { label: '林学', value: '林学' },
  { label: '园艺', value: '园艺' }
])

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 10,
  pageCount: 1
})

const handlePageChange = (page) => {
  pagination.value.page = page
}

// 数据加载状态
const loading = ref(false)

// 原始数据
const cityData = ref([])
const natureData = ref([])

// API调用函数
const fetchData = async () => {
  loading.value = true
  try {
    if (activeTab.value === 'city') {
      const response = await getEmploymentCityStats()
      // 将城市简称转换为全称
      cityData.value = (response.data.data || []).map(item => ({
        ...item,
        city: convertProvince(item.city)
      }))
    } else if (activeTab.value === 'nature') {
      const response = await getEmploymentNatureStats(
        // selectedYear.value,
        // selectedGrade.value,
        selectedCollege.value,
        selectedMajor.value
      )
      natureData.value = response.data.data || []
    }
    
    // 更新分页
    const currentData = activeTab.value === 'city' ? cityData.value : natureData.value
    pagination.value.pageCount = Math.ceil(currentData.length / pagination.value.pageSize)
    if (pagination.value.page > pagination.value.pageCount) {
      pagination.value.page = 1
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }

  console.log(cityData.value);
  

}

// 监听选项卡和筛选条件变化
// watch([activeTab, selectedYear, selectedGrade, selectedCollege, selectedMajor], () => {
watch([activeTab, selectedCollege, selectedMajor], () => {
  fetchData()
})

// 初始化数据
onMounted(() => {
  fetchData()
})

// 表格配置
const columns = computed(() => {
  if (activeTab.value === 'city') {
    return [
      { title: '城市', key: 'city', width: 120, ellipsis: { tooltip: true } },
      { title: '就业人数', key: 'count', width: 100 }
    ]
  } else {
    return [
      { title: '岗位性质', key: 'status', width: 120, ellipsis: { tooltip: true } },
      { title: '人数', key: 'count', width: 100 }
    ]
  }
})

// 计算表格数据
const tableData = computed(() => {
  const data = activeTab.value === 'city' ? cityData.value : natureData.value
  
  const start = (pagination.value.page - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return data.slice(start, end)
})

// 地图配置
const mapOption = computed(() => {
  const baseOption = {
    title: {
      text: '就业地市分布图',
      left: 'center',
      top: 0
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}'
    },
    visualMap: {
      min: 0,
      max: Math.max(...cityData.value.map(item => item.count), 1),
      left: 'right',
      top: 'bottom',
      text: ['高', '低'],
      calculable: true,
      inRange: {
        color: ['#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695']
      }
    },
    series: [
      {
        name: '就业人数',
        type: 'map',
        map: 'china',
        roam: true,
        emphasis: {
          label: {
            show: true
          }
        },
        data: cityData.value.map(item => ({
          name: item.city,
          value: item.count
        }))
      }
    ]
  }
  
  return baseOption
})

// 图表配置
const chartOption = computed(() => {
  const currentData = cityData.value
  
  const title = '就业地市统计'
  
  if (chartType.value === 'line') {
    return getLineOption(currentData, title)
  } else if (chartType.value === 'stack') {
    return getStackOption(currentData, title)
  } else if (chartType.value === 'data') {
    return getDataOption(currentData, title)
  } else {
    return getBarOption(currentData, title)
  }
})

// 岗位性质图表配置
const natureChartOption = computed(() => {
  const currentData = natureData.value
  
  return {
    title: {
      text: '岗位性质统计',
      left: 'center',
      top: 0
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: currentData.map(item => item.status)
    },
    series: [
      {
        name: '岗位性质',
        type: 'pie',
        radius: '50%',
        center: ['50%', '60%'],
        data: currentData.map(item => ({
          name: item.status,
          value: item.count
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
})

// 响应式图表配置
const isMobile = ref(window.innerWidth < 768)

const getBaseOption = (data, title) => {
  const itemCount = data.length
  const defaultShow = isMobile.value ? Math.min(5, itemCount) : Math.min(8, itemCount)
  const startValue = 0
  const endValue = defaultShow - 1
  
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: isMobile.value ? 14 : 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      confine: true
    },
    legend: {
      data: ['就业人数'],
      top: 30,
      itemWidth: isMobile.value ? 12 : 16,
      itemHeight: isMobile.value ? 12 : 16,
      textStyle: {
        fontSize: isMobile.value ? 12 : 14
      }
    },
    grid: {
      left: isMobile.value ? '5%' : '5%',
      right: '5%',
      bottom: isMobile.value ? '5%' : '10%',
      containLabel: true
    },
    dataZoom: [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        bottom: isMobile.value ? '0%' : '2%',
        height: 20,
        startValue,
        endValue,
        handleSize: 12,
        brushSelect: false,
        zoomLock: false,
        filterMode: 'filter',
        moveOnMouseMove: false,
        moveRate: 0.2,
        preventDefaultMouseMove: true
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        startValue,
        endValue,
        zoomOnMouseWheel: false,
        moveOnMouseMove: true,
        moveOnMouseWheel: true,
        preventDefaultMouseMove: true
      }
    ]
  }
}

function getBarOption(data, title) {
  const baseOption = getBaseOption(data, title)
  
  return {
    ...baseOption,
    xAxis: {
      type: 'category',
      data: data.map(item => item.city),
      axisLabel: {
        interval: 0,
        fontSize: isMobile.value ? 10 : 12,
        formatter: function(value) {
          return isMobile.value ? (value.length > 4 ? value.substring(0, 4) + '...' : value) : value
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: isMobile.value ? 10 : 12
      }
    },
    series: [
      {
        name: '就业人数',
        type: 'bar',
        barWidth: isMobile.value ? 12 : 20,
        itemStyle: {
          color: '#5470c6'
        },
        data: data.map(item => item.count)
      }
    ]
  }
}

function getLineOption(data, title) {
  const option = getBarOption(data, title)
  option.series[0].type = 'line'
  option.series[0].symbol = 'circle'
  option.series[0].symbolSize = isMobile.value ? 6 : 8
  option.series[0].lineStyle = {
    width: isMobile.value ? 2 : 3
  }
  return option
}

function getStackOption(data, title) {
  const option = getBarOption(data, title)
  option.series[0].stack = 'total'
  
  option.series.push({
    name: '总数',
    type: 'bar',
    stack: 'total',
    barWidth: isMobile.value ? 12 : 20,
    itemStyle: {
      color: 'transparent'
    },
    label: {
      show: true,
      position: 'top',
      fontSize: isMobile.value ? 10 : 12,
      formatter: function(params) {
        return params.value
      }
    },
    data: data.map(item => item.count)
  })
  
  return option
}

function getDataOption(data, title) {
  const baseOption = getBaseOption(data, title)
  
  return {
    ...baseOption,
    xAxis: {
      type: 'category',
      data: data.map(item => item.city),
      axisLabel: {
        interval: 0,
        fontSize: isMobile.value ? 10 : 12,
        formatter: function(value) {
          return isMobile.value ? (value.length > 4 ? value.substring(0, 4) + '...' : value) : value
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: isMobile.value ? 10 : 12
      }
    },
    series: [
      {
        name: '就业人数',
        type: 'bar',
        barWidth: isMobile.value ? 12 : 20,
        itemStyle: {
          color: '#91cc75'
        },
        data: data.map(item => item.count),
        label: {
          show: true,
          position: 'top',
          fontSize: isMobile.value ? 10 : 12,
          formatter: function(params) {
            return params.value
          }
        }
      }
    ]
  }
}

// 加载中国地图数据
let mapLoaded = false
chinaMap.then((res) => {
  if (!mapLoaded) {
    registerMap("china", res.data);
    mapLoaded = true;
  }
}).catch((err) => {
  console.error("Error loading China map data:", err);
  registerMap("china", {
    type: "FeatureCollection",
    features: []
  });
})

// 响应式处理
onMounted(() => {
  const updateIsMobile = () => {
    isMobile.value = window.innerWidth < 768
  }
  window.addEventListener('resize', updateIsMobile)
  updateIsMobile()
})
</script>

<style scoped>
.employment-statistics-container {
  padding: 16px;
  background-color: #f7f8fa;
  border-radius: 8px;
  max-width: 100%;
  overflow-x: hidden;
}

.filter-section {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.chart-type-section {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chart-wrapper {
  width: 100%;
  margin: 0 auto;
  margin-bottom: 30px;
}

.map-container,
.chart-container {
  width: 100%;
  margin: 0 auto;
}

.table-area {
  width: 100%;
  margin-top: 20px;
  overflow-x: auto;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 12px 0;
}

:deep(.n-data-table) {
  border-bottom: none;
  margin-bottom: 0;
  min-width: 100%;
}

:deep(.echarts) {
  padding-bottom: 20px;
}

:deep(.echarts-slider) {
  margin-top: 15px;
}

@media (max-width: 768px) {
  .employment-statistics-container {
    padding: 12px;
  }
  
  .filter-section,
  .chart-type-section {
    padding: 12px;
  }
  
  .filter-controls {
    flex-direction: column;
  }
  
  .filter-controls .n-select {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .chart-wrapper {
    margin-bottom: 0px;
  }
  
  .pagination-wrapper {
    margin-top: 15px;
    padding: 8px 0;
  }
  
  :deep(.n-radio-button) {
    padding: 0 8px;
    font-size: 12px;
  }
  
  :deep(.n-data-table th),
  :deep(.n-data-table td) {
    padding: 8px 12px;
    font-size: 12px;
  }
  
  :deep(.echarts-slider-handle) {
    width: 16px !important;
    height: 20px !important;
  }
}
</style>